#!/usr/bin/env bash

# PACKAGE: Gunther
# VERSION: 2.0
# DATE: 12/17/08
# AUTHOR(S): Zarrar Shehzad


# INCLUDE
source "$GUNTHERDIR/include/Asourceall.sh"

# VARIABLES
commandFile="${GUNTHERDIR}/commands/createROI_fromPeaks.sh" # can override this file at command-line
input=""
outputDir=`pwd`
roi_prefix=""
roi_radius=""
min_dist=10
thresh=2.3

# USAGE
function usage {
    changegood green
    echo
    echo "Usage"
    echo "  $0 [OPTIONS] -i <input file> -p <prefix> -r <radius> -o (output directory) -m (minumum distance between voxels)"
    echo "Program:"
    echo "   Will create masks by finding peaks in a 3D file and creating ROIs around those peaks"
    echo "Available Options:"
    echo "  -i: input; file to find and generate peaks from, often a thresh_zstat file (required)"
    echo "  -p: prefix; prefix for your generated files (required)"
    echo "  -r: radius; the radius (# VOXELS) for each generated ROI (required)"
    echo "  -t: thresh; the threshold to set before choosing the peaks (default: ${thresh})"
    echo "  -o: output directory; directory in which to output masks and other stuff (default: ${outputDir})"
    echo "  -m: minimum distance (# VOXELS): the minumum number of voxels between peaks (default: ${min_dist})"
    echo
    changebad
}

if [[ "$#" = 0 ]]; then
    usage
    exit 2
fi

# PARSE OPTIONS
while getopts ":i:p:r:t:m:o:dfIhl:L:" Option; do    
    case $Option in
        i ) input="$OPTARG"
            if [[ ! -e "$input" ]]; then
                zerror "Input file '${input}' does not exist"
                exit -1
            fi
    		;;
    	p ) roi_prefix="$OPTARG"
    	    ;;
    	r ) roi_radius="$OPTARG"
    	    ;;
    	t ) thresh="$OPTARG"
    	    ;;
    	m ) min_dist="$OPTARG"
    	    ;;
    	o ) outputDir="$OPTARG"
    	    if [[ ! -d "$outputDir" ]]; then
    	       zerror "Output directory '${outputDir}' does not exist"
    	       exit -1
    	    fi
    	    ;;
    	h ) usage 3
    	    exit 1
    	    ;;
    	: ) zerror "Argument value required for option '-$OPTARG'"
    	    exit -1
    	    ;;
    	? ) zerror "Unimplemented option '-$OPTARG' chosen"
    	    exit -1
    	    ;;
    	* ) zerror "Unknown error while processing options...continuing anyway"
    	    ;;
    esac
done

## save command
command="$@"
## move past any options
shift $((${OPTIND}-1))

# Give user feedback of what is running
ztitle "Executing: '$0 ${command}'"

# Checks
## output
if [[ -e ${outputDir}/amasks_${roi_prefix}.txt || -e ${outputDir}/${roi_prefix}.${gOUTPUT_TYPE} ]]; then
    zerror "Some sort of output (${outputDir}/amasks_${roi_prefix}.txt and ${outputDir}/${roi_prefix}.${gOUTPUT_TYPE}) already exists"
    exit -1
fi
## required options
if [[ -z "$input" || -z "$roi_prefix" || -z "$roi_radius" ]]; then
    zerror "You missed one of the required options: -i, -p, -r"
    exit -1
fi

# Run
tmpShortFile=`mktemp`

zinfo "Converting data to short"
zcmd "3dcalc -datum short -prefix ${tmpShortFile} -a ${input} -expr 'a'"

zinfo "Finding the peaks and creating one file with all of them"
zcmd "3dmaxima -input ${tmpShortFile}+tlrc -thresh ${thresh} -min_dist ${min_dist} -out_rad ${roi_radius} -spheres_1toN -prefix ${outputDir}/${roi_prefix}.${gOUTPUT_TYPE} -coords_only -dset_coords"
3dmaxima -input ${tmpShortFile}+tlrc -thresh ${thresh} -min_dist ${min_dist} -coords_only -dset_coords > ${outputDir}/${roi_prefix}_coords.txt

zinfo "Splitting up combined mask file into individual masks"
touch ${outputDir}/${roi_prefix}_names.txt
maxVal=`3dBrickStat -max ${outputDir}/${roi_prefix}.${gOUTPUT_TYPE}`
rangeVals=`count -digits 2 1 ${maxVal}`
for i in ${rangeVals}; do
    zcmd "fslmaths ${outputDir}/${roi_prefix}.${gOUTPUT_TYPE} -thr ${i} -uthr ${i} ${outputDir}/${roi_prefix}_${i}.${gOUTPUT_TYPE}"
    echo "${roi_prefix}_${i}" >> ${outputDir}/${roi_prefix}_names.txt
done

zinfo "Creating reference file ${outputDir}/amasks_${roi_prefix}.txt with mask names and coordinates"
pr -tm ${outputDir}/${roi_prefix}_names.txt ${outputDir}/${roi_prefix}_coords.txt | awk '{print $1,$2,$3,$4}' > ${outputDir}/${roi_prefix}_masks.txt

zinfo "Creating reference file ${outputDir}/acommand_${roi_prefix}.txt with command to create the ROIs"
echo "3dcalc -datum short -prefix ${tmpShortFile} -a ${input} -expr 'a'" > ${outputDir}/${roi_prefix}_command.txt
echo "3dmaxima -input ${tmpShortFile}+tlrc -thresh ${thresh} -min_dist ${min_dist} -out_rad ${roi_radius} -spheres_1toN -prefix ${outputDir}/${roi_prefix}.${gOUTPUT_TYPE} -coords_only -dset_coords" >> ${outputDir}/${roi_prefix}_command.txt
echo "rm ${tmpShortFile}*" >> ${outputDir}/${roi_prefix}_command.txt

zinfo "...cleaning up"
zcmd "rm ${outputDir}/${roi_prefix}_coords.txt ${outputDir}/${roi_prefix}_names.txt ${tmpShortFile}*"
